#include "film.h"

Film::Film() : data(0), width(0), height(0), ppp(0) {}
Film::~Film()
{
    //std::cout<<"~Film()"<<std::endl;
    if( data )
    {
        delete [] data;
        data=0;
    }
}
Film::Film(const Film &film) : data(new double[film.width*film.height*3*film.ppp*film.ppp]), width(film.width), height(film.height), ppp(film.ppp) { initFilm(); }
Film& Film::operator=(const Film &film) { return *this; }
Film::Film(unsigned int _width, unsigned int _height, unsigned int _ppp) :
    data(new double[_width*_height*3*_ppp*_ppp]), width(_width), height(_height), ppp(_ppp) { initFilm(); }

inline void Film::initFilm()
{
    double * ptr(data);
    for(unsigned int n=0 ; n < width*height*3*ppp*ppp ; n++)
        *(ptr++) = 0.0;
}

inline void Film::save(const std::string &outFile) const
{
    std::ofstream out(outFile.data(),std::ios::binary);
    out<<"P6\n";out<<"# This pgm file has been generated by Nico & Bichon"<<'\n';
    out<<width<<' '<< height<<'\n';
    out<<"255"<<'\n';

    char * tmp = new char[width*height*3];
    double        * src(data), color;
    char * dst(tmp);



    if( ppp == 1 )
    {
        src = data;
        for(unsigned int n=0 ; n<width*height*3 ; n++)
        {
            color = (*(src++));
            if( color > 1.0 )   color = 1.0;
            (*(dst++))= (char) (color*255.0);
        }
    }
    else if ( ppp == 2 )
    {
        unsigned int i,j;
        for(j=0 ; j<height ; j++)
        {
            src = data + ppp*(j)*width*3*ppp;
            for(i=0 ; i<width ; i++)
            {
                color = 0.25*(*(src) + *(src+3) + *(src+width*ppp*3) + *(src+width*ppp*3+3));
                if( color > 1.0 )   color = 1.0;
                (*(dst++))= (char) (color*255.0);
                src++;

                color = 0.25*(*(src) + *(src+3) + *(src+width*ppp*3) + *(src+width*ppp*3+3));
                if( color > 1.0 )   color = 1.0;
                (*(dst++))= (char) (color*255.0);
                src++;

                color = 0.25*(*(src) + *(src+3) + *(src+width*ppp*3) + *(src+width*ppp*3+3));
                if( color > 1.0 )   color = 1.0;
                (*(dst++))= (char) (color*255.0);
                src+=4;
            }
        }
    }
    out.write(tmp,width*height*3);
    out.close();
    delete [] tmp;
    tmp=0;

}


inline unsigned int Film::getWidth()  const
{
    return width*ppp;
}

inline unsigned int Film::getHeight() const
{
    return height*ppp;
}

inline double *     Film::getData()   const
{
    return data;
}

